<template>
  <tab-bar :tab-titles="tabTitles" :tab-styles="tabStyles" :duration="200" title-type="icon" @tabBarSelected="tabBarSelected">

    <div class="item-container">
      <farm-page class="flex"></farm-page>

      <wxc-dialog title="提示" content="还没有登录或登录过期，请重新登录！" :show="loginShow" :single="true" :is-checked="false" confirm-text="去登录" main-btn-color="#42bd56" @wxcDialogConfirmBtnClicked="goLogin"></wxc-dialog>
    </div>

    <div class="item-container">
      <credit-page class="flex"></credit-page>
    </div>

    <div class="item-container">
      <user-page class="flex"></user-page>
    </div>

  </tab-bar>
</template>


<script>
import { Utils, WxcDialog } from 'weex-ui'
import config from './index.js'
import TabBar from '../components/tab-bar.vue'
import FarmPage from './farm/index.vue'
import CreditPage from './credit/index.vue'
import UserPage from './user/index.vue'
import {
  DEFAULT_CLIENT_ID,
  STORAGE_LOGIN,
  STORAGE_FARM,
  STORAGE_USER,
  STORAGE_VERSION_IGNORE,
  EVENT_GET_USER,
  EVENT_GET_FARM,
  STORAGE_FIRST_LAUNCH,
  EVENT_GET_USER_REFRESH,
  EVENT_GET_FARM_REFRESH
} from '../plugins/constant'
const globalEvent = weex.requireModule('globalEvent')

export default {
  components: {
    WxcDialog,
    TabBar,
    FarmPage,
    CreditPage,
    UserPage
  },
  data: () => ({
    user: {},
    farm: {},
    defaultClientId: '',
    loginShow: false,
    tabTitles: config.tabTitles,
    tabStyles: config.tabStyles,
    homeBackClickTime: +new Date(),

    // 版本检测
    appVersionInfo: {},
    newest: {},
    downloadUrl: '',
    ignoreVersion: ''
  }),
  eros: {
    beforeBackAppear(params) {
      if (params && params.type === 1) {
        this.setFarm(true)
      }
    }
  },
  created() {
    this.androidFinishApp()
    this.setNavigationInfo()

    this.$event.on(EVENT_GET_FARM_REFRESH, () => { this.setFarm() })
    this.$event.on(EVENT_GET_USER_REFRESH, () => { this.setUser() })

    // 用户和农场数据
    this.getUser()

    // 设置内容区域的高度
    // const tabPageHeight = Utils.env.getPageHeight()
    // 如果页面没有导航栏，可以用下面这个计算高度的方法
    // const tabPageHeight = weex.config.env.deviceHeight / weex.config.env.deviceWidth * 750
    // this.contentStyle = { height: (tabPageHeight - this.tabStyles.height) + 'px', width: '750px' }

    this.checkVersion()
  },
  methods: {
    androidFinishApp() {
      globalEvent.addEventListener('homeBack', options => {
        const timeNow = new Date().getTime()
        if (timeNow - this.homeBackClickTime > 2000) {
          this.$notice.toast({ message: '再按一次退出应用' })
          this.homeBackClickTime = timeNow
        } else {
          this.$router.finish()
        }
      })
    },
    setNavigationInfo() {
      this.$navigator.setNavigationInfo({
        navShow: false,
        statusBarStyle: 'LightContent'
      })
    },
    tabBarSelected(e) {
      // const index = e.page
    },
    getUser() {
      // 从storage中获取用户信息（可以添加多个农场，每次打开APP必须得重新获取）
      // const user = this.$storage.getSync(STORAGE_USER)
      // if (user) {
      //   this.getFarmInfo(user.defaultClientId)
      //   return this.$event.emit(EVENT_GET_USER, user)
      // }

      // 无用户信息，从API中获取
      this.setUser()
    },
    getFarmInfo() {
      // 从storage中获取农场信息
      const farm = this.$storage.getSync(STORAGE_FARM)
      if (farm) { return this.$event.emit(EVENT_GET_FARM, farm) }
      this.setFarm()
    },
    setUser() {
      this.$http({
        method: 'GET',
        name: 'auth.me'
      }).then(res => {
        this.user = res
        this.$storage.setSync(STORAGE_USER, res)
        this.$event.emit(EVENT_GET_USER, res)
        if (res.defaultClientId !== this.defaultClientId) {
          this.defaultClientId = res.defaultClientId
          this.getFarmInfo()
        }
      }).catch(err => {
        if (err && err.status >= 400 && err.status <= 499) {
          this.loginShow = true
        }
      })
    },
    setFarm() {
      if (this.user.defaultClientId === DEFAULT_CLIENT_ID) { return }
      this.$http({
        method: 'GET',
        name: 'industrial.farm.info',
        data: {
          farmId: this.user.defaultClientId
        }
      }).then(res => {
        this.farm = res
        this.$storage.setSync(STORAGE_FARM, res)
        this.$event.emit(EVENT_GET_FARM, res)
      }).catch(err => {
        if (err && err.status >= 400 && err.status <= 499) {
          this.loginShow = true
        }
      })
    },
    // 没有登录或登录过期
    goLogin() {
      this.loginShow = false
      this.$storage.removeAllSync()
      this.$storage.setSync(STORAGE_FIRST_LAUNCH, '1')
      this.$router.setHomePage('/pages/user/login.js')
    },

    // 版本检查
    checkVersion() {
      Promise.all([this.getVersionInfo(), this.getNesest()]).then(res => {
        this.appVersionInfo = res[0] || {}
        this.newest = res[1] || {}
        this.getDownloadUrl().then(res => {
          this.downloadUrl = res
          this.checkUpdate()
        })
      }).catch(err => {
        console.log(err)
      })
    },
    checkUpdate() {
      // 无法获取版本信息、版本号大于等于最新版本
      const newestCode = +this.newest.version_code || 0
      if (!this.appVersionInfo.versionCode ||
        !this.newest.version_code ||
        (this.appVersionInfo.versionCode >= newestCode)
      ) { return }

      this.ignoreVersion = this.$storage.getSync(STORAGE_VERSION_IGNORE) || ''
      if (this.ignoreVersion && +this.ignoreVersion === newestCode) { return }

      this.$dialog.show({
        title: '发现新版本',
        content: this.newest.description || '',
        positiveText: '立即更新',
        negativeText: '取消',
        neutralText: '忽略该版本',
        onPositive: () => {
          this.startDownloadAndInstall()
        },
        onNeutral: () => {
          this.$storage.setSync(STORAGE_VERSION_IGNORE, newestCode)
        }
      })
    },
    getVersionInfo() {
      return new Promise(async (resolve, reject) => {
        const [res, err] = await this.$utils.pm(this.$version.getVersionInfo())
        if (res) { resolve(res) } else { reject(err) }
      })
    },
    getNesest() {
      return new Promise(async (resolve, reject) => {
        const [res, err] = await this.$utils.pm(this.$api.getData({
          server: 'agr_chain',
          table: 'app_version_view',
          params: {
            index: 1,
            size: 1,
            'release_status.eq': 1
          },
          order: {
            version_code: 'desc'
          },
          errorMsg: '获取数据失败'
        }))
        if (res && res.data && res.data.length) {
          const item = res.data[0]
          item.links = []
          item.description = item.description ? item.description.replace(/<br\/>/g, '\n').replace(/&nbsp;/g, ' ') : ''
          const channelNames = this.getSplit(item.channel_name)
          const channelUrls = this.getSplit(item.channel_url)
          const channelIds = this.getSplit(item.channel_id)
          for (let i = 0; i < channelNames.length; i++) {
            item.links.push({
              channelId: channelIds[i],
              channelName: channelNames[i],
              channelUrl: channelUrls[i]
            })
          }
          resolve(item)
        } else {
          reject(err)
        }
      })
    },
    getSplit(str, splitor = ',') {
      return str ? str.split(splitor) : []
    },
    // 从最新版本获取对应渠道的下载地址
    getDownloadUrl() {
      return new Promise((resolve, reject) => {
        const links = this.newest.links || []
        if (!links.length) {
          return reject('无下载地址')
        }
        let downloadUrl = ''
        let defaultUrl = ''
        for (const link of links) {
          if (link.channelId === this.appVersionInfo.channel) {
            downloadUrl = link.channelUrl
            break
          }
          if (link.channelId === 'WeiMi') {
            defaultUrl = link.channelUrl
          }
        }
        if (!downloadUrl) {
          downloadUrl = defaultUrl
        }
        if (!downloadUrl) {
          reject('无下载地址')
        } else {
          resolve(downloadUrl)
        }
      })
    },
    startDownloadAndInstall() {
      if (!this.downloadUrl) {
        return this.$notice.toast({ message: '无下载地址' })
      }
      this.$version.downloadAndInstall({
        downloadUrl: this.downloadUrl,
        versionTips: this.newest.version_tips
      }).then(res => {
        this.$notice.toast({ message: '开始下载，下载完成后自动安装' })
      }).catch(err => {
        // this.$notice.toast({ message: '更新失败，请稍后再试' })
      })
    },
  }
};
</script>

<style lang="scss" scoped>
.flex {
  flex: 1;
}
.item-container {
  width: 750px;
  flex: 1;
}
</style>